
package com.alifi.crm.dal;

import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.sql.Types;
import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;

/**
 * @author wenjing.huangwj
 * 枚举类型的ibatis类型处理器基类
 * 
 */
public abstract class EnumTypeHandler<E extends EnumStringInterface> implements
		TypeHandlerCallback {
	
	private int sqlType;
	
	private Class<E> enumClass;
	
	public EnumTypeHandler() {
		this(Types.VARCHAR);
	}
	
	@SuppressWarnings("unchecked")
	protected EnumTypeHandler(int sqlType) {
		this.sqlType = sqlType;
		this.enumClass = (Class<E>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	@Override
	public Object getResult(ResultGetter getter) throws SQLException {
		String value = getter.getString();
		if (value != null) {
			return EnumUtils.findByCode(enumClass, value);
		} else {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setParameter(ParameterSetter setter, Object parameter)
			throws SQLException {
		if (parameter != null) {
			setter.setString(((E) parameter).code());
		} else {
			setter.setNull(sqlType);
		}
	}

	@Override
	public Object valueOf(String s) {
		throw new UnsupportedOperationException();
	}
}
